package com.my.mvvmrapid.ui.main.fragment.homeali;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.libra.Utils;
import com.my.mvvmrapid.BR;
import com.my.mvvmrapid.R;
import com.my.mvvmrapid.constants.Constants;
import com.my.mvvmrapid.databinding.FragmentHomeAliBinding;
import com.my.mvvmrapid.ui.main.fragment.homeali.data.DEBUG;
import com.my.mvvmrapid.ui.main.fragment.homeali.data.RatioTextView;
import com.my.mvvmrapid.ui.main.fragment.homeali.data.SimpleImgView;
import com.my.mvvmrapid.ui.main.fragment.homeali.data.TestView;
import com.my.mvvmrapid.ui.main.fragment.homeali.data.TestViewHolder;
import com.my.mvvmrapid.ui.main.fragment.homeali.data.TestViewHolderCell;
import com.my.mvvmrapid.ui.main.fragment.homeali.data.VVTEST;
import com.tmall.wireless.tangram.TangramBuilder;
import com.tmall.wireless.tangram.TangramEngine;
import com.tmall.wireless.tangram.structure.viewcreator.ViewHolderCreator;
import com.tmall.wireless.tangram.util.IInnerImageSetter;
import com.zhongjh.mvvmrapid.base.ui.BaseFragment;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import io.reactivex.annotations.NonNull;

/**
 * 阿里列表
 */
public class HomeALiFragment extends BaseFragment<FragmentHomeAliBinding, HomeALiViewModel> {

    TangramBuilder.InnerBuilder builder;
    TangramEngine engine;

    public static HomeALiFragment newInstance() {
        return new HomeALiFragment();
    }

    @Override
    public int initContentView(@NotNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_home_ali;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (engine != null) {
            engine.destroy();
        }
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public void initParam() {

    }

    @Override
    public void initData() {

        // Step 2: register build=in cells and cards
        builder = TangramBuilder.newInnerBuilder(getContext());

        // Step 3: register business cells and cards
        builder.registerCell(1, TestView.class);
        builder.registerCell(10, SimpleImgView.class);
        builder.registerCell(2, SimpleImgView.class);
        builder.registerCell(4, RatioTextView.class);
        builder.registerCell(110,
                TestViewHolderCell.class,
                new ViewHolderCreator<>(R.layout.layout_homeali_item_holder, TestViewHolder.class, TextView.class));
        builder.registerVirtualView("vvtest");

        // Step 4: new engine
        engine = builder.build();
        engine.setVirtualViewTemplate(VVTEST.BIN);
        engine.setVirtualViewTemplate(DEBUG.BIN);
        Utils.setUedScreenWidth(720);

//        //Step 5: add card load support if you have card that loading cells async
//        engine.addCardLoadSupport(new CardLoadSupport(
//                new AsyncLoader() {
//                    @Override
//                    public void loadData(Card card, @NonNull final LoadedCallback callback) {
//                        Log.w("Load Card", card.load);
//
//                        mMainHandler.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                // do loading
//                                JSONArray cells = new JSONArray();
//
//                                for (int i = 0; i < 10; i++) {
//                                    try {
//                                        JSONObject obj = new JSONObject();
//                                        obj.put("type", 1);
//                                        obj.put("msg", "async loaded");
//                                        JSONObject style = new JSONObject();
//                                        style.put("bgColor", "#FF1111");
//                                        obj.put("style", style.toString());
//                                        cells.put(obj);
//                                    } catch (JSONException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//
//                                // callback.fail(false);
//                                callback.finish(engine.parseComponent(cells));
//                            }
//                        }, 200);
//                    }
//                },
//
//                new AsyncPageLoader() {
//                    @Override
//                    public void loadData(final int page, @NonNull final Card card, @NonNull final LoadedCallback callback) {
//                        mMainHandler.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                Log.w("Load page", card.load + " page " + page);
//                                JSONArray cells = new JSONArray();
//                                for (int i = 0; i < 9; i++) {
//                                    try {
//                                        JSONObject obj = new JSONObject();
//                                        obj.put("type", 1);
//                                        obj.put("msg", "async page loaded, params: " + card.getParams().toString());
//                                        cells.put(obj);
//                                    } catch (JSONException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                                List<BaseCell> cs = engine.parseComponent(cells);
//
//                                if (card.page == 1) {
//                                    GroupBasicAdapter<Card, ?> adapter = engine.getGroupBasicAdapter();
//
//                                    card.setCells(cs);
//                                    adapter.refreshWithoutNotify();
//                                    Range<Integer> range = adapter.getCardRange(card);
//
//                                    adapter.notifyItemRemoved(range.getLower());
//                                    adapter.notifyItemRangeInserted(range.getLower(), cs.size());
//
//                                } else
//                                    card.addCells(cs);
//
//                                //mock load 6 pages
//                                callback.finish(card.page != 6);
//                                card.notifyDataChange();
//                            }
//                        }, 400);
//                    }
//                }));
//        engine.addSimpleClickSupport(new SampleClickSupport());
//
//        // Step 6: enable auto load more if your page's data is lazy loaded
//        engine.enableAutoLoadMore(true);
//        engine.register(InternalErrorSupport.class, new SampleErrorSupport());

        // Step 7: bind recyclerView to engine
        engine.bindView(binding.rvMain);

        // Step 8: listener recyclerView onScroll event to trigger auto load more
        binding.rvMain.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                engine.onScrolled();
            }
        });

        //Step 9: set an offset to fix card
        engine.getLayoutManager().setFixOffset(0, 40, 0, 0);

        //Step 10: get tangram data and pass it to engine
        String json = new String(getAssertsFile(getContext()));
        JSONArray data = null;
        try {
            data = new JSONArray(json);
            engine.setData(data);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void initViewObservable() {

    }

    private static byte[] getAssertsFile(Context context) {
        InputStream inputStream = null;
        AssetManager assetManager = context.getAssets();
        try {
            inputStream = assetManager.open(Constants.DATA_JSON);
            if (inputStream == null) {
                return null;
            }

            int length;
            try (BufferedInputStream bis = new BufferedInputStream(inputStream)) {
                length = bis.available();
                byte[] data = new byte[length];
                bis.read(data);

                return data;
            } catch (IOException ignored) {

            }

            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


}
